<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    @register="registerModal"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :destroyOnClose="true"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} - {{ descriptor?.name }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #scriptLangSlot="{ model, field }">
        <Tabs v-model:activeKey="model[field]" animated>
          <TabPane key="TBEL" :forceRender="true" tab="TBEL">
            <CodeEditor v-model:value="model['tbelScript']" :mode="MODE.JS" />
          </TabPane>
          <TabPane key="JS" :forceRender="true" tab="JavaScript">
            <CodeEditor v-model:value="model['jsScript']" :mode="MODE.JS" />
          </TabPane>
        </Tabs>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup name="RuleChainNodeDataForm">
  import { Tabs, TabPane } from 'ant-design-vue';
  import { CodeEditor, MODE } from '/@/components/CodeEditor';
  import { ref, unref, computed, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { RuleNode } from '/@/api/thingsborad/ruleChain';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { ComponentDescriptor } from '/@/api/thingsborad/componentDescriptor';
  import { EntityType } from '/@/enums/entityTypeEnum';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { getSchemas, getNodeData, processingData } from './nodeForm.data';
  import { has } from 'lodash-es';

  const emit = defineEmits(['success', 'cancel', 'register']);
  const { t } = useI18n('things');
  const flag = ref<boolean>(false);
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const [registerForm, { setProps, validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  const nodeId = ref('');
  const ruleChainId = ref<object>();
  const descriptor = ref<ComponentDescriptor>();
  const record = ref<RuleNode>();
  const isNewNode = ref<boolean>(false);
  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: record.value?.id?.id ? '编辑规则节点' : '添加规则节点',
  }));

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true, ...modalStyleSetting });
    descriptor.value = data.descriptor;
    setProps({
      schemas: getSchemas(descriptor.value),
    });
    record.value = data.data || {};

    if (record.value?.name) {
      const arr = Object.keys(record.value.configuration);
      if (arr.length > 0 && has(record.value, arr[0])) {
        setFieldsValue({
          ...record.value,
        });
      } else {
        Object.keys(record.value.configuration).forEach((key) => {
          record.value && (record.value[key] = record.value.configuration[key]);
        });

        const res = processingData('display', record.value, descriptor.value);
        setFieldsValue({
          description: record.value?.additionalInfo?.description,
          ...res,
        });
      }
    }
    isNewNode.value = false;
    if (data.isNewNode) {
      isNewNode.value = true;
    }
    nodeId.value = data.nodeId || '';
    ruleChainId.value = data.ruleChainId;

    setModalProps({ loading: false });
  });

  async function handleSubmit() {
    flag.value = !flag.value;
    try {
      setModalProps({ confirmLoading: true });
      nextTick(async () => {
        const data = await validate();
        const res = processingData('save', data, descriptor.value);
        setTimeout(closeModal);
        emit('success', getNodeData(res, descriptor, EntityType, nodeId, ruleChainId, isNewNode));
      });
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleCancel() {
    setTimeout(closeModal);
    if (record.value?.id?.id) {
      // emit('success', { ...record.value });
    } else {
      emit('cancel', { nodeId: nodeId.value });
    }
  }
</script>
